import { Materials, OrderInfoItem } from '@/types/orderInfo';
import { groupBy, isEmpty, transform } from 'lodash-es';

export function materials2OrderInfo(
  materials: Materials,
  orderIds: string[],
): OrderInfoItem[] {
  if (Object.values(materials).every(isEmpty)) {
    return [];
  }

  const groupedPlanks = groupBy(materials.planks, 'orderId');
  const groupedMoldings = groupBy(materials.moldings, 'orderId');
  const groupedFinishedProducts = groupBy(
    materials.finishedProducts,
    'orderId',
  );

  return transform(
    orderIds,
    (result, orderId) => {
      const planks = groupedPlanks[orderId] ?? [];
      const moldings = groupedMoldings[orderId] ?? [];
      const finishedProducts = groupedFinishedProducts[orderId] ?? [];
      let orderInfoItem = result.record[orderId];
      const orderName = planks[0].orderName;
      if (orderInfoItem === undefined) {
        orderInfoItem = result.record[orderId] = {
          orderId,
          orderName,
          planks: [],
          moldings: [],
          finishedProducts: [],
        };
        result.orderInfo.push(orderInfoItem);
      }
      orderInfoItem.planks.push(...planks);
      orderInfoItem.moldings.push(...moldings);
      orderInfoItem.finishedProducts.push(...finishedProducts);
    },
    {
      orderInfo: [] as OrderInfoItem[],
      record: {} as Record<string, OrderInfoItem>,
    },
  ).orderInfo;
}
